package com.testDemo.service;

import java.io.FileInputStream;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.testDemo.dao.TestDao;
import com.testDemo.enrty.Element;
import com.testDemo.enrty.TestDemoResult;
import com.testDemo.utils.MethodPageUtils;
import com.testDemo.utils.TestUtils;

/**
 * @author cuij
 * @version 创建时间：2017-6-13 上午11:33:48
 *          程序的简单说明
 */
@Service
public class TestDemoServicelmpl implements TestDemoService {

    @Resource
    private TestDao dao;

    @Override
    public TestDemoResult getMethodPage(String methodName) throws Exception {
        // 开始搬运王总的代码，希望可以看懂
        Map retMap = new HashMap<String, String>();
        List<String> exceptions = new ArrayList<String>();
        String methodPage = "";

        // 转换接口名,获取不带中文描述的接口名
        String method = "";
        if (methodName.contains("(")) {
            method = methodName.substring(methodName.lastIndexOf("/") + 1, methodName.indexOf("("));
        }
        else if (methodName.contains("（")) {
            method = methodName.substring(methodName.lastIndexOf("/") + 1, methodName.indexOf("（"));
        }
        // 查询数据库看是否有生成的页面,若有直接使用,否则读取本地接口规范生成页面,并入库
        List<Map> methodInfo = dao.selectMethodInfoByMethod(method);
        if (!TestUtils.isEmpty(methodInfo) && !TestUtils.isEmpty(methodInfo.get(0).get("METHOD_PAGE"))) {
            methodPage = TestUtils.ClobToString((Clob) methodInfo.get(0).get("METHOD_PAGE"));
        }
        else {
            String interfacePath = TestUtils.INTERFACE_EXCEL_PATH + methodName + ".xlsx";
            XSSFWorkbook work = new XSSFWorkbook(new FileInputStream(interfacePath));
            // 获取接口规范所在的sheet页
            Sheet sheet = work.getSheet("HttpRest协议");
            Element msg = MethodPageUtils.getRowContent(sheet, exceptions);
            if (TestUtils.isEmpty(msg.getChildElements())) {
                exceptions.add("接口:" + interfacePath + "生成模板失败,请查看");
            }
            else {
                // 将生成的页面入库
                String isRightPage = TestUtils.isEmpty(exceptions) ? "1" : "0";
                Map dataMap = TestUtils.asMap("method", method, "methodPage", msg.getHtmlContent(), "isRightPage",
                        isRightPage);
                dao.upDateMethodPage(dataMap);
            }
            methodPage = msg.getHtmlContent();
        }
        // 从库中查询接口对应的所有bizkey,bizkey的存放方式为XX|XX|XX
        List<String> bizkeys = dao.selectBizkeyByMethod(method);
        if (TestUtils.isEmpty(bizkeys)) {
            exceptions.add("根据接口:" + methodName + ",未获取到对应的bizkey");
        }
        else {
            String[] bizkey = bizkeys.get(0).split("\\|");
            bizkeys = Arrays.asList(bizkey);
        }
        retMap.put("exception", exceptions);
        retMap.put("bizkeys", bizkeys);
        retMap.put("htmlcontent", methodPage);
        return new TestDemoResult(TestDemoResult.SUCCESS_CODE, "success", retMap);
    }

    @Override
    public TestDemoResult getMethodList() {
        // 从数据库中查询出所有的接口
        List<String> methods = dao.selectAllMethod();
        return new TestDemoResult(TestDemoResult.SUCCESS_CODE, "查询成功", methods);
    }

    @Override
    public TestDemoResult getAppkeyList() throws Exception {
        // 先查库获取到所有的省份 appkey 工号,并根据三联菜单格式拼装参数
        List<Map> appkeys = dao.selectAllAppKeyInfo();
        List<Map> provinceList = new ArrayList<Map>();
        Map provinceMap = new HashMap();
        List<Map> appList = new ArrayList<Map>();

        // 根据层级拼装层级
        provinceMap.put("name", TestUtils.changeProvince(appkeys.get(0).get("PROVINCE_CODE"), true));
        for (Map appkey : appkeys) {
            String provinceName = TestUtils.changeProvince(appkey.get("PROVINCE_CODE"), true);
            if (!TestUtils.isEmpty(provinceMap) && !provinceName.equals(provinceMap.get("name"))) {
                provinceMap.put("cityList", appList);
                provinceList.add(provinceMap);
                provinceMap = new HashMap();
                provinceMap.put("name", provinceName);
                appList = new ArrayList<Map>();
            }
            Map appMap = new HashMap();
            appMap.put("name", appkey.get("APPKEY"));
            List<String> operators = new ArrayList<String>();
            operators.add(appkey.get("OPERATOR_ID_I") + "");
            if (!com.test.TestUtils.isEmpty(appkey.get("OPERATOR_ID_II"))) {
                operators.add(appkey.get("OPERATOR_ID_II") + "");
            }
            appMap.put("areaList", operators);
            appList.add(appMap);
        }
        if (!TestUtils.isEmpty(appList)) {
            provinceMap.put("cityList", appList);
            provinceList.add(provinceMap);
        }
        return new TestDemoResult(TestDemoResult.SUCCESS_CODE, "查询成功", provinceList);
    }

    @Override
    public TestDemoResult getOperatorInfo(String operatorId) {
        List<Map> operators = dao.selectOperatorInfo(operatorId);
        if (TestUtils.isEmpty(operators)) {
            return new TestDemoResult(TestDemoResult.ERROR_CODE, "根据工号[" + operatorId + "]未查询到对应的工号信息", "");
        }
        return new TestDemoResult(TestDemoResult.SUCCESS_CODE, "查询成功", operators.get(0));
    }
}
